<!-- eslint-disable vue/no-deprecated-v-on-native-modifier -->
<template>
  <div :class="'style_' + info.name" class="dams_form">
    <!-- 内部构建表单 -->
    <el-form
      ref="ruleForm"
      v-loading="loading"
      :inline="true"
      :label-position="labelPosition"
      :model="formData"
      :rules="rules"
      style="display: flex; flex-wrap: wrap"
      @submit.native.prevent
    >
      <el-form-item
        v-for="(v, i) in listData"
        :key="i"
        :class="'item_' + v.type"
        :label="v.labelHidden == true ? '' : v.label"
        :prop="v.name"
        :validate-on-rule-change="false"
      >
        <template #label v-if="v.slot">
          <span>
            <span class="span-box">
              <span>{{ v.label }}</span>
              <span style="font-size: 12px; color: #af3636">
                <span v-if="v.helpSlot">
                  {{ v.slotContent }}
                </span>
                <span v-else>
                  <span>{{ translateTitle('Dams.ApplicationInterface.帮助') }}</span>
                  <el-tooltip effect="dark" placement="top" style="diaplay: inline">
                    <template #content :style="{ color: v.fontColor ? v.fontColor : '#000' }">
                      <pre>
                    <code>
                      {{v.slotContent}}
                    </code>
                  </pre>
                    </template>
                    <vui-icon icon="question-fill" />
                  </el-tooltip>
                </span>
              </span>
            </span>
          </span>
        </template>

        <!-- 文本框 -->
        <template v-if="v.type == 'input'">
          <el-input
            v-model="formData[v.name]"
            :clearable="true"
            :disabled="getDisabled(v)"
            :placeholder="v.placeholder ? v.placeholder : translateTitle('Dams.ApplicationInterface.请输入内容')"
            :show-password="v.showPassword ? v.showPassword : false"
          />
        </template>
        <!-- 用户周期 -->
        <template v-if="v.type == 'userPeriod'">
          <div class="flex">
            <el-input
              v-model="formData[v.name.split(',')[0]]"
              :clearable="true"
              :disabled="getDisabled(v)"
              :placeholder="v.placeholder ? v.placeholder : translateTitle('Dams.ApplicationInterface.请输入内容')"
              :show-password="v.showPassword ? v.showPassword : false"
            />
            <el-select
              v-model="formData[v.name.split(',')[1]]"
              :collapse-tags="v.isMultiple ? v.isMultiple : false"
              :collapse-tags-tooltip="v.isMultiple ? v.isMultiple : false"
              :disabled="getDisabled(v)"
              :filterable="v.filterable ? v.filterable : false"
              :multiple="v.isMultiple ? v.isMultiple : false"
              @change="changeSelect(v.name, $event)"
            >
              <el-option v-for="item in v.options" :key="item.LABEL" :label="item.LABEL" :value="item.CODE" />
            </el-select>
          </div>
        </template>
        <!-- 文本域 -->
        <template v-if="v.type == 'textarea_in_out'">
          <div v-if="listData[i].name == 'DAO_SP_PARAMS_OUT' || listData[i].name == 'DAO_SP_PARAMS_IN'">
            <CodeEditor :ref="'VuiCodeEditor_'" v-model="formData[v.name]" />
          </div>
        </template>
        <!-- 文本域 -->
        <template v-if="v.type == 'textarea'">
          <!-- <el-input
            v-show="0"
            v-model="formData[v.name]"
            :clearable="true"
            :disabled="getDisabled(v)"
            :placeholder="translateTitle('Dams.ApplicationInterface.请输入内容')"
            :rows="10"
            type="textarea"
          /> -->
          <CodeEditor :ref="'VuiCodeEditor_' + i + '_' + v.name" v-model="formData[v.name]" :height="v.height" />
        </template>
        <template v-if="v.type == 'selectRemote'">
          <el-select
            v-model="formData[v.name]"
            filterable
            remote
            :remote-method="
              (val) => {
                remoteMethod(val, v)
              }
            "
          >
            <el-option v-for="item in v.options" :key="item.CODE_ID" :label="item.NAME" :value="item.CODE_ID" />
          </el-select>
        </template>
        <!-- 多选 -->
        <template v-if="v.type == 'select'">
          <el-select
            v-model="formData[v.name]"
            :clearable="true"
            :collapse-tags="v.isMultiple ? v.isMultiple : false"
            :collapse-tags-tooltip="v.isMultiple ? v.isMultiple : false"
            :disabled="getDisabled(v)"
            :filterable="v.filterable ? v.filterable : false"
            :multiple="v.isMultiple ? v.isMultiple : false"
            @change="changeSelect(v.name, $event)"
          >
            <el-option v-for="item in v.options" :key="item.LABEL" :label="item.LABEL" :value="item.CODE" />
          </el-select>
        </template>
        <!-- 级联 -->
        <template v-if="v.type == 'cascader'">
          <el-cascader v-model="formData[v.name]" :options="v.options" :props="v.props" :show-all-levels="false" />
        </template>
        <!-- 级联 -->
        <template v-if="v.type == 'switch'">
          <el-switch v-model="formData[v.name]" :active-value="v.activeValue" :inactive-value="v.inactiveValue" />
        </template>
        <!-- 单选 -->
        <template v-if="v.type == 'radio'">
          <el-radio-group v-model="formData[v.name]" :disabled="getDisabled(v)">
            <el-radio v-for="item in v.options" :key="item.LABEL" :label="item.CODE">{{ item.LABEL }}</el-radio>
          </el-radio-group>
        </template>
        <!-- 时间配置 -->
        <template v-if="v.type == 'vuicron'">
          <VuiCron v-if="vuiCronShow" v-model="formData[v.name]" />
        </template>
        <!-- 数字输入框 -->
        <template v-if="v.type == 'numInput'">
          <el-input-number v-model="formData[v.name]" :label="translateTitle('Dams.ApplicationInterface.描述文字')" :min="0" />
        </template>
        <!-- 图片上传 -->
        <template v-if="v.type == 'imgUpload'">
          <el-upload
            :action="`${configSetting.domain}${configSetting.baseUrl}`"
            :before-upload="
              (res) => {
                return beforeAvatarUpload(res, v.name)
              }
            "
            class="avatar-uploader"
            :data="postData"
            :headers="headersData"
            name="uploadFile"
            :on-success="
              (res) => {
                return handleAvatarSuccess(res, v.name)
              }
            "
            :show-file-list="false"
          >
            <img v-if="formData[v.name]" class="avatar" :src="formData[v.name + 'url'] || formData[v.name]" />
            <vui-icon v-else class="avatar-uploader-icon" icon="add-line" />
            <vui-icon v-if="formData[v.name]" class="delete-img" icon="delete-bin-line" @click.stop="imgDelete(v.name)" />
          </el-upload>
        </template>
        <!-- 时间范围 -->
        <template v-if="v.type == 'datePicker'">
          <el-date-picker
            v-model="formData[v.name]"
            :disabled-date="v.disabledDate ? disabledDate : ''"
            :end-placeholder="translateTitle('Dams.ApplicationInterface.结束日期')"
            :range-separator="translateTitle('Dams.ApplicationInterface.至')"
            :start-placeholder="translateTitle('Dams.ApplicationInterface.开始日期')"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="v.defaultTime ? defaultTime : []"
          />
        </template>
        <!-- 时间范围 -->
        <template v-if="v.type == 'dateTime'">
          <el-date-picker
            v-model="formData[v.name]"
            :placeholder="translateTitle('Dams.ApplicationInterface.选择日期时间')"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </template>
        <!-- 按钮 -->
        <template v-if="v.type == 'button'">
          <el-button :loading="subLoading" type="primary" @click="onSubmit(v.label, 'ruleForm')">
            {{ v.label }}
          </el-button>
        </template>
        <!-- 标题 -->
        <div v-if="v.type == 'line'" class="line">
          <span>{{ v.label }}</span>
          <span v-if="v.key == 'sqlConfig'" style="font-size: 12px; color: #af3636">
            <span>{{ translateTitle('Dams.ApplicationInterface.帮助') }}</span>
            <el-tooltip effect="dark" placement="top" style="diaplay: inline">
              <template #content>
                <pre>
                    <code>
                      {{jsHintContent}}
                    </code>
                  </pre>
              </template>
              <vui-icon icon="question-fill" />
            </el-tooltip>
          </span>
        </div>
      </el-form-item>
      <slot></slot>
    </el-form>
  </div>
</template>

<script>
  import isArray from 'lodash/isArray'
  import CodeEditor from './codeEditor'
  import { getList } from '../api/home'
  import { GFCD } from '@/utils/utils'
  import cloneDeep from 'lodash/cloneDeep'
  import { translateTitle } from '@/utils/i18n'
  import { mapGetters } from 'vuex'
  import request from '@/utils/request'
  const imgKeys = ['BACKGROUND_IMAGE_BASE64', 'LOGO_IMAGE_BASE64']
  export default {
    name: 'Forms',
    components: {
      CodeEditor,
    },
    props: {
      subLoading: {
        type: Boolean,
        default: false,
      },
      labelPosition: {
        type: String,
        default: 'left',
      },
      type: {
        type: String,
        default: function () {
          return 'edit'
        },
      },
      // 传的数据 可以看serverConfig.json
      list: {
        type: Object,
        default: function () {
          return {}
        },
      },
      dataFrom: {
        type: Object,
        default: function () {
          return {}
        },
      },

      dialogNum: {
        type: Number,
        default: function () {
          return 0
        },
      },
      open: {
        type: Boolean,
        default: function () {
          return false
        },
      },
      name: {
        type: String,
        default: function () {
          return ''
        },
      },
      // 是否自动调用查询接口
      autoQuery: {
        type: Boolean,
        default: function () {
          return false
        },
      },
      vuiCronShow: {
        type: Boolean,
        default: () => {
          return true
        },
      },
    },
    emits: ['newPassword_editor'],
    data() {
      return {
        defaultTime: [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)],
        postData: {
          method: 'dams.file.common.upload',
          data: JSON.stringify({}),
        },
        loading: false,
        rules: {},
        info: {},
        //post 值
        formData: {},
        //字段
        formField: [],
        configSetting: {},
        // 按钮区别
        btnName: '',
        jsHintContent: `
        1.查询sql示例：
          sku_code  from sku_tab where 1=1;sku=#{sku};and customerid=#LIKE#({{customerid}});and addtime=#{#DATE_TIME#}
            说明：
              1.1 分号隔开表示：动态条件，前端如果不传或者为空的字段 sql条件回自动去掉
              1.2 如果有动态条件 必须写 where 1=1
              1.3 ‘#{}’ 代表传值变量 没有sql注入的风险
              1.4 ‘{{}}’代表传值变量  有sql注入的风险
              1.5 ‘#’开头个‘#’结尾的是系统内置常量 详见常量说明
              1.6 第一个 select 不要写
              1.7 sql字段只能 有一个 ‘*’ 的查询出险
        2.新增sql示例 (填写到《SQL-字段名》 文本框中)
          sku=#{sku_web};说明：sku:代表数据库字段  #{} 里面的 sku_web 代表前端传来的字段名，多个英文分号隔开
        3.删除sql 示例(填写到 《SQL-WHERE 条件》 中)
          sku=#{sku_web}说明：sku:代表数据库字段  #{} 里面的 sku_web 代表前端传来的字段名，多个英文分号隔开
        4.修改sql示例
        4.1更新的字段：（填写到SQL-字段名 文本框中）
          sku=#{sku_web}说明：sku:代表数据库字段  #{} 里面的 sku_web 代表前端传来的字段名，多个英文分号隔开
        4.2 where条件：（填写到《SQL-WHERE 条件》 中文本框中）
          customerid =#{ customerid _web}说明：sku:代表数据库字段  #{} 里面的 customerid _web 代表前端传来的字段名，多个英文分号隔开
        5.SP填写：
            5.1 sp名称 填写到 《SP-名称》文本框中
            5.2 sp 参数 填写到《SP-参数》文本框中
        参数填写说明：例如：#{org_id};*;#{#USER_ID#};OUT_RETURN_CODE;OUT_OTHER….
        多个参数英文分号隔开，出参必须以大写的 OUT_ 开头 并且第一个出参 必须是：OUT_RETURN_COD
        6.所有查询 sql语句 where 需要权限控制的 参照以下sql 写法（mybatis）
            <where>
              //组织
              <choose>
                  <when test="ORG_ID != null and ORG_ID != ''">AND p.ORG_ID IN(#{#IN#:ORG_ID})//前端传的</when>
                  <otherwise>AND p.ORG_ID IN(#{#IN#:#AUTH_ORG_ID#})//常量授权的</otherwise>
              </choose>
              //仓库
              <choose>
                  <when test="WAREHOUSE_ID != null and WAREHOUSE_ID != ''">AND p.WAREHOUSE_ID IN (#{#IN#:WAREHOUSE_ID}) //前端传的</when>
                  <otherwise>AND p.WAREHOUSE_ID IN(#{#IN#:#AUTH_WH_ID#})//常量授权的</otherwise>
              </choose>
              //货主
              <choose>
                  <when test="OWNER_ID != null and OWNER_ID != ''">AND p.OWNER_ID in (#{#IN#:OWNER_ID})  //前端传的</when>
                  <otherwise>AND p.OWNER_ID IN(#{#IN#:#OWNER_ID#})  //常量授权的</otherwise>
              </choose>
          </where>
        `,
      }
    },

    computed: {
      listData: function () {
        console.log(this.formField)
        return this.formField.filter(function (it) {
          return !it.hidden
        })
      },
      headersData() {
        return {
          token: this.token,
        }
      },
      ...mapGetters({
        token: 'user/token',
      }),
      // get
    },
    watch: {
      dialogNum: {
        deep: true,
        handler(newval) {
          this.formDataShow(newval)
        },
      },
      dataFrom: {
        deep: true,
        handler(newval) {
          console.log(newval)
          this.fieldFiltrate(newval)
          this.formData = newval
          // imgKeys.forEach(r => {
          //   if (this.formData[r] && this.formData[r].indexOf('data:image') == -1) {
          //   this.getImg(this.formData[r], r)
          // }
          // })
          this.getImgKeys()
        },
      },
      open: {
        deep: true,
        handler(newval) {
          if (newval) {
            this.refresh()
          }
        },
      },
      list() {
        this.init()
      },
    },
    created() {
      this.configSetting = GFCD('dams')
      console.log(this.configSetting)
      this.formData = this.dataFrom
      this.getImgKeys()
      this.init()
      this.refresh()
      if (this.autoQuery) {
        console.log(`${this.name}_forms_on_${this.info.name}`, this.formData)
        this.$pub(`${this.name}_forms_on_${this.info.name}`, this.formData)
      }
    },
    methods: {
      getImgKeys() {
        imgKeys.forEach((r) => {
          if (this.formData[r] && this.formData[r].indexOf('data:image') == -1) {
            this.getImg(this.formData[r], r)
          }
        })
      },
      disabledDate(time) {
        const nowDate = Date.now()
        const dateObjUnix = time.getTime()
        return nowDate < dateObjUnix
      },
      async remoteMethod(val, v) {
        let url = GFCD('dams')
        if (val !== '') {
          let res = await getList(`${url.domain}${url.baseUrl}`, {
            data: JSON.stringify({
              '#LIMIT#': 1,
              '#PAGE_SIZE#': 99999,
              SUB_SYSTEM: 'DAMS',
              name: val,
            }),
            method: 'dams.language.pack.select.query',
          })
          v.options = res.data['dams.language.pack.select.query'].data
        } else {
          v.options = []
        }
      },
      translateTitle,
      fieldFiltrate(obj) {
        let oldField = cloneDeep(this.formField)
        let result = [
          {
            type: 'input',
            name: 'LOGIN_TITLE',
            label: translateTitle('Dams.ApplicationInterface.登录标题'),
            labelHidden: false,
          },
          {
            type: 'input',
            name: 'LOGIN_DESC',
            label: translateTitle('Dams.ApplicationInterface.登录描述'),
            labelHidden: false,
          },
          {
            type: 'imgUpload',
            name: 'LOGIN_IMAGE_BASE64',
            label: translateTitle('Dams.ApplicationInterface.登录LOGO'),
            labelHidden: false,
          },
        ]
        if (this.name == 'ApplyList') {
          if (obj.APP_CODE == 'DAMS') {
            if (oldField.length > 14) {
              this.formField.splice(13, 3)
            }
            this.formField.splice(13, 0, ...result)
          } else {
            if (oldField.length > 14) {
              this.formField.splice(13, 3)
            }
          }
        }
      },
      setFormData(form) {
        for (const key in form) {
          const element = form[key]
          if (key.indexOf(',') > -1 && element) {
            form[key.split(',')[1]] = element.charAt(element.length - 1)
            form[key.split(',')[0]] = element.substring(0, element.length - 1)
          }
        }
      },
      imgChange(image, name) {
        let reader = new FileReader() //实例化文件读取对象
        reader.readAsDataURL(image) //将文件读取为 DataURL,也就是base64编码
        // reader.readAsDataURL(image) //将文件读取为 DataURL,也就是base64编码
        reader.onload = (ev) => {
          //文件读取成功完成时触发
          let dataURL = ev.target.result //获得文件读取成功后的DataURL,也就是base64编码
          this.$nextTick(() => {
            this.formData[name] = dataURL
          })
        }
      },
      imgDelete(name) {
        this.formData[name] = ''
        this.formData[name + 'url'] = ''
      },
      handleAvatarSuccess(res, name) {
        console.log(res, name)
        if (res.code === '00000') {
          this.formData[name] = res.data[0]['#FILE_SEQ#']
          this.getImg(res.data[0]['#FILE_SEQ#'], name)
        } else {
          this.$message({
            type: 'error',
            message: res.msg,
          })
          this.loading = false
        }
      },
      async getImg(FILE_SEQ, name) {
        let res = await request({
          url: `${this.configSetting.domain}${this.configSetting.baseUrl}`,
          method: 'post',
          data: {
            data: JSON.stringify({ FILE_SEQ: FILE_SEQ, '#OUTPUT_TYPE#': 'base64' }),
            method: 'dams.file.common.download',
          },
          // responseType: 'blob',
        })
        console.log(res)
        this.loading = false
        this.formData[name + 'url'] = `data:image/${res.data[0].FILE_SUFFIX};base64,${res.data[0].BASE64_STRING}`
      },
      beforeAvatarUpload(file, name) {
        // this.formData[name] = file.slice(0)
        //暂时不做验证
        // const isJPG = file.type === 'image/jpeg'
        // if (!isJPG) {
        //   this.$message.error('上传头像图片只能是 JPG 格式!')
        // } else {
        // this.imgChange(file, name)
        // }
        const fileMaxSize = 3 * 1024 * 1024
        if (file.size > fileMaxSize) {
          this.$message({
            type: 'error',
            message: translateTitle('Dams.ApplicationInterface.文件不能超过3M'),
          })
          return false
        }
        this.loading = true
        console.log(file, name)
      },
      getRules(row) {
        if (row.isRules && (row.type == 'input' || row.type == 'vuicron' || row.type == 'textarea')) {
          this.rules[row.name] = [{ required: true, message: translateTitle('Dams.ApplicationInterface.请输入内容'), trigger: 'blur' }]
          if (row.regExp) {
            let reg = new RegExp(row.regExp)
            var validate = (rule, value, callback) => {
              if (!reg.test(value)) {
                callback(new Error(row.rulesHint))
              } else {
                callback()
              }
            }
            this.rules[row.name] = [{ required: true, validator: validate, trigger: 'blur' }]
          }
        }
        if (
          row.isRules &&
          (row.type == 'select' || row.type == 'cascader' || row.type == 'radio' || row.type == 'dateTime' || row.type == 'selectRemote')
        ) {
          this.rules[row.name] = [{ required: true, message: translateTitle('Dams.ApplicationInterface.请选择内容'), trigger: 'change' }]
        }
      },
      init() {
        let form = this.list.form
        if (form) {
          if (this.name == 'saveTestPage') {
            this.formField = this.list.form.fieldTest
          } else {
            this.formField = this.list.form.field
          }

          this.formDataShow(this.dialogNum)
          this.info = form
          this.formField.forEach((row) => {
            if (row.name == 'SQL_TYPE' && this.formData['SQL_TYPE']) {
              this.getFieldShow(this.formData['SQL_TYPE'], 'y')
            }
          })
          // console.log(this.formData)
          if (this.formData.DAO_SP_PARAMS) {
            let spObj = this.splitSpParams(this.formData.DAO_SP_PARAMS)
            this.formData.DAO_SP_PARAMS_IN = spObj.in_params
            this.formData.DAO_SP_PARAMS_OUT = spObj.out_params
          }
          if (this.formData.TIMER_GROUP) {
            let item = this.formField.find((el) => el.name == 'TIMER_GROUP')
            let itemHost = item.options.find((el) => el.CODE == this.formData.TIMER_GROUP)
            this.formData.TIMER_HOST = itemHost.TIMER_HOST
          }
          this.setFormData(this.formData)
          this.fieldFiltrate(this.formData)
          console.log(this.formData)
        }
      },
      refresh() {
        let that = this
        this.$nextTick(function () {
          for (let item in that.$refs) {
            try {
              if (isArray(that.$refs[item]) && that.$refs[item].length > 0) {
                that.$refs[item][0].refresh()
              }
              // if (isObject(that.$refs[item])) {
              //   that.$refs[item].refresh()
              // }
            } catch (e) {
              console.log(e)
            }
          }
        })
      },
      splitSpParams(str) {
        let returnObj = {}
        let arr = str.replace(/\s+/g, '').split(';')
        let out_params = ''
        let in_params = ''
        let exp = /^out_/i
        for (let index in arr) {
          if (arr[index].length < 1) {
            continue
          }
          if (exp.test(arr[index])) {
            out_params += arr[index] + ';'
          } else {
            in_params += arr[index] + ';'
          }
        }
        in_params = in_params.substring(0, in_params.length - 1)
        out_params = out_params.substring(0, out_params.length - 1)
        returnObj['in_params'] = in_params
        returnObj['out_params'] = out_params
        return returnObj
      },
      // 表格渲染按钮接口地址定义
      formDataShow(num) {
        switch (num) {
          case 1:
            this.formField = this.list.form.field
            // this.addPostUrl = 'dams.handle.flow.add'
            // this.modifyPostUrl = 'dams.handle.flow.edit'
            break
          case 2:
            this.formField = this.list.form.fieldMapping
            // this.addPostUrl = 'dams.sql.filed.map.add'
            // this.modifyPostUrl = 'dams.sql.filed.map.edit'
            break
          case 3:
            this.formField = this.list.form.fieldMapping3
            // this.addPostUrl = 'dams.sql.filed.map.add'
            // this.modifyPostUrl = 'dams.sql.filed.map.edit'
            break
          case 4:
            this.formField = this.list.form.fieldMapping4
            break
        }
        this.rules = {}
        for (let index = 0; index < this.formField.length; index++) {
          const element = this.formField[index]
          this.getRules(element)
        }
      },
      onSubmit(btnName, formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.btnName = btnName
            if (`${this.name}_forms_on_${this.info.name}` == `${this.name}_forms_on_search`) {
              if (btnName == translateTitle('Dams.ApplicationInterface.重置')) {
                this.$pub(`${this.name}_forms_reset_${this.info.name}`, {})
              } else {
                this.$pub(`${this.name}_forms_on_${this.info.name}`, this.formData)
              }
            } else if (`${this.name}_forms_on_${this.info.name}` == `${this.name}_forms_on_dialog`) {
              // 校验SQL按钮
              if (btnName == translateTitle('Dams.ApplicationInterface.校验SQL')) {
                this.$pub(`${this.name}_forms_on_${this.info.name}`, '校验SQL')
              } else {
                if (this.name == 'newPassword') {
                  this.$emit('newPassword_editor')
                } else {
                  console.log(`${this.name}_forms_on_${this.info.name}`)
                  this.$pub(`${this.name}_forms_on_${this.info.name}`, '提交')
                }
              }
            } else {
              if (btnName == translateTitle('Dams.ApplicationInterface.校验SQL')) {
                this.$pub(`${this.name}_forms_on_${this.info.name}`, '校验SQL')
              } else {
                this.$pub(`${this.name}_forms_on_${this.info.name}`, this.formData)
              }
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      async changeSelect(name, e) {
        console.log(name, e)
        console.log(`${this.name}_forms_changeSelect_${this.info.name}`)
        this.$pub(`${this.name}_forms_changeSelect_${this.info.name}`, { name, e })
        if (name == 'TIMER_GROUP') {
          let item = this.formField.find((el) => el.name == name)
          let itemHost = item.options.find((el) => el.CODE == e)
          this.formData.TIMER_HOST = itemHost.TIMER_HOST
        }
        if (name == 'ACTIVE' && e == 'N') {
          this.type == 'add' ? (this.formField[6].disabled_add = true) : (this.formField[6].disabled_edit = true)
          this.formField[7].value = 'N'
          this.formData.DEFAULT_ACTIVE = 'N'
        } else if (name == 'ACTIVE' && e == 'Y') {
          this.type == 'add' ? (this.formField[6].disabled_add = false) : (this.formField[6].disabled_edit = false)
        }
        if (name == 'type') {
          let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
            method: 'dams.query.api.templ',
            data: JSON.stringify({ '#LIMIT#': 1, '#PAGE_SIZE#': 9999, API_NAME: e }),
          })
          const keyArr = ['ID', 'API_NAME', 'API_CN_DESC', 'API_EN_DESC', 'SUB_SYSTEM']
          let resData = res.data['dams.query.api.templ'].data[0]
          for (const key in resData) {
            if (keyArr.indexOf(key) == -1) {
              this.formData[key] = resData[key]
            }
          }
        }
        if (name == 'SQL_TYPE') {
          this.getFieldShow(e)
        }
      },
      getFieldShow(e, i) {
        let showObj = {
          INSERT: ['SQL_FIELD', 'PRIMARY_KEY_FIELD', 'NATIVE_SQL'],
          UPDATE: ['SQL_WHERE', 'SQL_FIELD'],
          DELETE: ['SQL_WHERE'],
          SELECT: ['NATIVE_SQL', 'SQL_ORDER_BY', 'NATIVE_SQL_MYSQL', 'NATIVE_SQL_ORACLE', 'NATIVE_SQL_SQLSERVER'],
          SP: ['DAO_SP_PARAMS_IN', 'DAO_SP_PARAMS_OUT'],
        }
        let arr = [
          'SQL_FIELD',
          'PRIMARY_KEY_FIELD',
          'SQL_WHERE',
          'NATIVE_SQL',
          'SQL_ORDER_BY',
          'DAO_SP_PARAMS_IN',
          'DAO_SP_PARAMS_OUT',
          'NATIVE_SQL_MYSQL',
          'NATIVE_SQL_ORACLE',
          'NATIVE_SQL_SQLSERVER',
        ]
        for (const key in showObj) {
          if (e == key) {
            this.formField.forEach((row) => {
              if (showObj[key].indexOf(row.name) > -1) {
                row.hidden = false
              }
              if (arr.indexOf(row.name) > -1 && showObj[key].indexOf(row.name) == -1) {
                row.hidden = true
              }
            })
          }
        }
        if (i != 'y') {
          arr.forEach((item) => {
            this.formData[item] = ''
          })
        }
      },
      getDisabled(v) {
        return this.type == 'add' ? v.disabled_add : v.disabled_edit
      },
    },
  }
</script>

<style lang="scss" scoped>
  @import '@/ve/styles/elements.scss';
  .dams_form {
    :deep() .el-form-item__label {
      margin-top: 0;
      line-height: 32px;
    }
  }

  .item_textarea_in_out {
    width: calc(43% + 41px) !important;
  }
  .item_textarea {
    width: calc(92% + 30px) !important;
  }
  .item_line {
    width: calc(92% + 30px) !important;
    border-bottom: 1px dashed #ccc;
    margin: 10px 0px !important;
    .line {
      width: 100% !important;
      height: 30px;
      background: rgb(221, 220, 220) !important;
      font-size: 20px !important;
      padding: 0px 20px;
    }
  }
  .delete-img {
    position: absolute;
    right: 0;
    bottom: -10px;
  }
  :deep() {
    .el-cascader {
      width: 100%;
    }
    .el-input__inner {
      height: 26px;
      line-height: 26px;
      border-radius: 2px;
      padding: 0 6px;
    }
    .el-form-item--small.el-form-item {
      margin-bottom: 10px;
      width: auto;
    }
    .el-upload {
      border: 1px dashed #d9d9d9;
      // border-radius: 6px;
      cursor: pointer;
      position: relative;
      height: 32px;
      width: 100%;
      // overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      color: #8c939d;
      width: 100%;
      height: 100%;
    }
    .avatar {
      width: 100%;
      height: 32px;
      display: block;
    }
    .el-form-item--small .el-form-item__content {
      line-height: 32px;
    }
  }
</style>
